package com.tnovoselec.android.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {

    private static MessageDigest md5MessageDigest = null;
    private static StringBuilder stringBuilder = null;

    static {
	try {
	    md5MessageDigest = MessageDigest.getInstance("MD5");
	} catch (NoSuchAlgorithmException ex) {
	    // DO nothing
	}

	stringBuilder = new StringBuilder();
    }

    private Md5Util() {
	super();
    }

    /**
     * Converts String into MD5 String
     * 
     * @param s
     * @return MD5 encoded String
     */
    public synchronized static String md5(String s) {
	md5MessageDigest.reset();
	md5MessageDigest.update(s.getBytes());

	byte digest[] = md5MessageDigest.digest();

	stringBuilder.setLength(0);
	for (int i = 0; i < digest.length; i++) {
	    stringBuilder.append(Integer.toHexString(0xFF & digest[i]));
	}

	return stringBuilder.toString();
    }
}
